﻿using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using MapDownloader.Core.Models;

namespace MapDownloader.Core.Core
{
   internal class DefaultImageProxy : BaseImageProxy
   {
      private static readonly bool Win7OrLater = Stuff.IsRunningOnWin7orLater();
      
      public override BaseImage FromStream(Stream stream)
      {
         var result = new MapImage
         {
            Img = Image.FromStream(stream, true, !Win7OrLater)
         };
         return result;
      }

      public override bool Save(Stream stream, BaseImage image)
      {
         var result = image as MapImage;
         var ok = true;

         if ( result?.Img != null)
            try
            {
               result.Img.Save(stream, ImageFormat.Png);
            }
            catch
            {
               try
               {
                  stream.Seek(0, SeekOrigin.Begin);
                  result.Img.Save(stream, ImageFormat.Jpeg);
               }
               catch
               {
                  ok = false;
               }
            }
         else
            ok = false;

         return ok;
      }

   }
}